<template>
  <div>
    <Card :bordered="false">
      <Row>
        <Col span="12">
        <ButtonGroup>
          <Button type="primary" @click="openAddModal">新增</Button>
        </ButtonGroup>
        </Col>
        <Col span="12" style="text-align: right">
        <Input v-model="txtSearch" placeholder="请输入停车场名称/编号" style="width: 200px"/>
        <Button icon="ios-search" type="primary" @click="getParkingList"></Button>
        </Col>
      </Row>
    </Card>
    <Card :bordered="false">
      <Table height="500" :columns="columns" :data="parkingList"></Table>
    </Card>
    <!--新增停车场-->
    <Modal
      v-model="modal.add.status"
      :title="modal.add.title"
      draggable
      scrollable
      width="1000"
      :top="0"
      @on-cancel="modalDefineCancel('modal.add.form')">
      <Row>
        <Col span="16">
        <Form ref= 'modal.add.form' :model="modal.add.form" :label-width="80" :rules='ruleValidate'>
          <FormItem label="名称" prop='name'>
            <Input v-model="modal.add.form.name" placeholder="请输入停车场名称"></Input>
          </FormItem>
          <FormItem label="编号" prop='code'>
            <Input v-model="modal.add.form.code" placeholder="请输入编号" @on-blur="checkLotCode(modal.add.form.code)"></Input>
            <label class="codeLb" v-if="lotCodeError">编号已存在</label>
          </FormItem>
          <FormItem label="所属机构" prop='orgName'>
            <Input v-if="false" disabled v-model="modal.add.form.orgId" placeholder="请输入机构名称"></Input>
            <Input disabled v-model="modal.add.form.orgName" placeholder="请输入机构名称"></Input>
          </FormItem>
          <FormItem label="经度" prop='longitude'>
            <Input @on-blur="changeAddMapMarker" v-model="modal.add.form.longitude" placeholder="例如：108.831294"></Input>
          </FormItem>
          <FormItem label="纬度" prop='latitude'>
            <Input @on-blur="changeAddMapMarker" v-model="modal.add.form.latitude" placeholder="例如：34.248405"></Input>
          </FormItem>
          <FormItem label="地址" prop='address'>
            <Input v-model="modal.add.form.address" placeholder="例如：陕西省西安市高新区科技二路清华科技园"></Input>
          </FormItem>
          <FormItem label="收费标准" prop='price'>
            <Input v-model="modal.add.form.price" placeholder="例如：2元/小时"></Input>
          </FormItem>
          <FormItem label="总车位数" prop='totalNum'>
            <Input v-model="modal.add.form.totalNum" placeholder="例如：1000"></Input>
          </FormItem>
        </Form>
        </Col>
        <Col span="6">
        <div id="mapAdd" style="width: 300px;height: 430px;margin-left: 10px;">
        </div>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="default" @click="handleReset('modal.add.form')">取消</Button>
        <Button type="primary" @click="handleSubmit('modal.add.form')">确定</Button>
      </div>
    </Modal>
    <!--修改停车场-->
    <Modal
      v-model="modal.update.status"
      :title="modal.update.title"
      width="1000"
      :top="0"
      @on-cancel="modalDefineCancel('modal.update.form')">
      <Row>
        <Col span="16">
        <Form ref= 'modal.update.form' :model="modal.update.form" :label-width="80" :rules='ruleValidate'>
          <FormItem label="名称" prop='name'>
            <Input v-model="modal.update.form.name" placeholder="请输入停车场名称"></Input>
          </FormItem>
          <FormItem label="编号" prop='code'>
            <Input v-model="modal.update.form.code" placeholder="请输入编号" @on-blur="checkLotCode(modal.update.form.code,modal.update.form.id)"></Input>
            <label class="codeLb" v-if="lotCodeError">编号已存在</label>
          </FormItem>
          <FormItem label="所属机构" prop='orgName'>
            <Input v-if="false" disabled v-model="modal.update.form.orgId" placeholder="请输入机构名称"></Input>
            <Input disabled v-model="modal.update.form.orgName" placeholder="请输入机构名称"></Input>
          </FormItem>
          <FormItem label="经度" prop='longitude'>
            <Input @on-blur="changeUpdateMapMarker" v-model="modal.update.form.longitude" placeholder="例如：108.831294"></Input>
          </FormItem>
          <FormItem label="纬度" prop='latitude'>
            <Input @on-blur="changeUpdateMapMarker" v-model="modal.update.form.latitude" placeholder="例如：34.248405"></Input>
          </FormItem>
          <FormItem label="地址">
            <Input v-model="modal.update.form.address" placeholder="例如：陕西省西安市高新区科技二路清华科技园"></Input>
          </FormItem>
          <FormItem label="收费标准">
            <Input v-model="modal.update.form.price" placeholder="例如：2元/小时"></Input>
          </FormItem>
          <FormItem label="总车位数" prop='totalNum'>
            <Input v-model="modal.update.form.totalNum" placeholder="例如：1000"></Input>
          </FormItem>
        </Form>
        </Col>
        <Col span="6">
        <div id="mapUpdate" style="width: 300px;height: 430px;margin-left: 10px;">
        </div>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="default" @click="handleReset('modal.update.form')">取消</Button>
        <Button type="primary" @click="handleSubmit('modal.update.form')">确定</Button>
      </div>
    </Modal>
    <!--删除停车场-->
    <Modal
      v-model="modal.delete.status"
      :title="modal.delete.title"
      @on-ok="deleteParking">
      确定删除停车场{{modal.delete.parkingName}}吗？
    </Modal>
  </div>
</template>

<script>
  import {getParkingLots, addParkingLot} from "../../api/parkingLot"
  import urlSource from '../../api/urlSource'
  import moment from 'moment'

  let mapAdd;
  let markerAdds=[];
  let mapUpdate;
  let markerUpdates=[];
  export default {
    name: "lot",
    components: {},
    data() {
      let validateName = function(rule, value, callback){
        if(!value){
          return callback(new Error("请输入名称"));
        }else{
          callback();
        }
      };
      let validateCode = function(rule, value, callback){
        if(!value){
          return callback(new Error("请输入编号"));
        }else{
          callback();
        }
      };
      let validateOrgName = function(rule, value, callback){
        if(!value){
          return callback(new Error("请输入所属机构"));
        }else{
          callback();
        }
      };
      let validateLongitude = function(rule, value, callback){
        if(!value){
          return callback(new Error("请输入经度"));
        }else{
          callback();
        }
      };
      let validateLatitude = function(rule, value, callback){
        if(!value){
          return callback(new Error("请输入纬度"));
        }else{
          callback();
        }
      };
      return {
        txtSearch: "",
        tmpMarker: '',
        modal: {
          add: {
            status: false,
            title: "新增停车场",
            form: {
              id: "", //主键id
              name: "", //停车场名称
              code: "", //停车场编号
              useNum: "", //使用的车位数
              totalNum: "", //总车位数
              // unit: this.$store.state.user.access, //所属单位
              orgId: this.$store.state.user.orgId,
              price: "",//价格
              address: "",//地址
              longitude: "",//经度
              latitude: "",//纬度
              userId: ""//所属单位id
            }
          },
          update: {
            status: false,
            title: "修改停车场",
            form: {
              id: "", //主键id
              name: "", //停车场名称
              code: "", //停车场编号
              useNum: "", //使用的车位数
              totalNum: "", //总车位数
              // unit: "", //所属单位
              orgId: this.$store.state.user.orgId,
              price: "",//价格
              address: "",//地址
              longitude: "",//经度
              latitude: "",//纬度
              userId: ""//所属单位id
            }
          },
          delete: {
            title: "系统提示",
            status: false,
            id: "",
            parkingName: ""
          }
        },
        columns: [
          {
            type: 'index',
            width: 60,
            align: 'center'
          },
          {
            title: '名称',
            key: 'name'
          },
          {
            title: '编号',
            key: 'code'
          },
          {
            title: '车位数',
            key: 'desNum',
            render: (h, params) => {
              return h('div', [
                h('div', params.row.totalNum)
              ]);
            }
          },
/*
          {
            title: '剩余车位',
            key: 'desNum',
            render: (h, params) => {
              return h('div', [
                h('div', params.row.useNum + "/" + params.row.totalNum)
              ]);
            }
          },
*/
          {
            title: '所属机构',
            key: 'orgId',
            render: (h,params) =>{
              let orgName = '';
              this.orgList.forEach((data) => {
                if(params.row.orgId==data.id){
                  orgName = data.orgName;
                }
              });
              return h('div',[
                h('div',orgName)
              ]);
            }
          },
          {
            title: '收费标准',
            key: 'price'
          },
          {
            title: '创建时间',
            key: 'createTime',
          },
          {
            title: '操作',
            key: 'id',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.openUpdateModal(params)
                    }
                  }
                }, '修改'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.modal.delete.status = true;
                      this.modal.delete.id = params.row.id;
                      this.modal.delete.parkingName = params.row.name;
                    }
                  }
                }, '删除')
              ]);
            }
          }
        ],
        parkingList: [],
        orgList: [],
        lotCodeError: false,
        ruleValidate:{
          name : [{required: true,validator: validateName,trigger: 'blur'}],
          code : [{required: true,validator: validateCode,trigger: 'blur'}],
          orgName : [{required: true,validator: validateOrgName,trigger: 'blur'}],
          longitude : [{required: true,validator: validateLongitude,type: 'string',trigger: 'blur'}],
          latitude : [{required: true,validator: validateLatitude,trigger: 'blur'}],
          totalNum : [{required: false},{ message: '车位数应为整数', trigger:'change', pattern:/^[0-9]+$/}]
        },
      }
    },
    methods: {
      handleReset (name) {
        if(name=='modal.add.form'){
          this.modal.add.status=false;
        }else{
          this.modal.update.status=false;
        }
        this.lotCodeError = false;
        this.$refs[name].resetFields();
      },
      modalDefineCancel (name){
        this.lotCodeError = false;
        this.$refs[name].resetFields();
      },
      handleSubmit (name,lotId) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            if(this.lotCodeError){
              this.$Message.error('请正确填写停车场编号');
              return;
            }
            if(name=='modal.add.form'){//添加表单校验
              this.addLot();
            }else{//修改表单校验
              this.updateLot();
            }
          } else {
            this.$Message.error('请正确填写信息');
          }
        })
      },
      getOrgList(){
        let currentOrgId = this.$store.state.user.orgId;
        let url = urlSource.apiUrl + 'org/getParentOrg/' + currentOrgId;
        this.$http.get(url).then(res => {
          this.orgList = res.data;
        }).catch(err => {

        })
      },
      //校验停车位编号
      checkLotCode(lotCode,id){
        if(lotCode!=null && lotCode!='' && lotCode!=undefined){
          let url = urlSource.apiUrl + 'parkingLots/checkLotCode';
          let param = {code:lotCode};
          param.id = id ? id : null;
          param.orgId = this.$store.state.user.orgId;
          this.$http.post(url,param).then(res => {
            this.lotCodeError = res.data;
          }).catch(err => {

          })
        }else{
          this.lotCodeError = false;
        }
      },
      initMap() {
        mapAdd = new AMap.Map('mapAdd', {
          resizeEnable: true,
          zoom: 9,
          center: [108.947509,34.260749]
        });

        mapAdd.plugin(["AMap.ToolBar"], function() {
          mapAdd.addControl(new AMap.ToolBar());
        });

        let _this = this;
        mapAdd.on('click', function(e) {
          _this.clearMarker(mapAdd);
          _this.modal.add.form.longitude = e.lnglat.getLng();
          _this.modal.add.form.latitude = e.lnglat.getLat();

          let marker = new AMap.Marker({
            icon: new AMap.Icon({
              size: new AMap.Size(40, 40),//图标大小
              imageSize: new AMap.Size(40, 40),
              image: urlSource.imageUrl + "icon/parking.png"
            }),
            position: [e.lnglat.getLng(), e.lnglat.getLat()],
          });
          mapAdd.setCenter([e.lnglat.getLng(), e.lnglat.getLat()]); //设置地图中心点
          marker.setMap(mapAdd);
          _this.tmpMarker = marker;
        });
      },
      clearMarker(baseMap){
        if(this.tmpMarker){
          baseMap.remove(this.tmpMarker);
        }
      },
      initUpdateMap(lng,lat){
        mapUpdate = new AMap.Map('mapUpdate', {
          resizeEnable: true,
          zoom: 9,
          center: [108.947509,34.260749]
        });
        let _this = this;
        mapUpdate.on('click', function(e) {
          _this.clearMarker(mapUpdate);
          _this.modal.update.form.longitude = e.lnglat.getLng();
          _this.modal.update.form.latitude = e.lnglat.getLat();

          let marker = new AMap.Marker({
            icon: new AMap.Icon({
              size: new AMap.Size(40, 40),//图标大小
              imageSize: new AMap.Size(40, 40),
              image: urlSource.imageUrl + "icon/parking.png"
            }),
            position: [e.lnglat.getLng(), e.lnglat.getLat()],
          });
          mapUpdate.setCenter([e.lnglat.getLng(), e.lnglat.getLat()]); //设置地图中心点
          marker.setMap(mapUpdate);
          _this.tmpMarker = marker;
        });
        let marker = new AMap.Marker({
          icon: new AMap.Icon({
            size: new AMap.Size(40, 40),//图标大小
            imageSize: new AMap.Size(40, 40),
            image: urlSource.imageUrl + "icon/parking.png"
          }),
          position: [lng, lat],
        });
        mapUpdate.setCenter([lng, lat]); //设置地图中心点
        marker.setMap(mapUpdate);
        markerUpdates.push(marker)
        _this.tmpMarker = marker;
      },
      //新增停车场，添加地图位置
      changeAddMapMarker() {
        let lng = this.modal.add.form.longitude;
        let lat = this.modal.add.form.latitude;
        if (lat != "" && lng != "") {
          let marker = new AMap.Marker({
            icon: new AMap.Icon({
              size: new AMap.Size(40, 40),//图标大小
              imageSize: new AMap.Size(40, 40),
              image: urlSource.imageUrl + "icon/parking.png"
            }),
            position: [lng, lat],
          });
          markerAdds.push(marker);
          mapAdd.remove(markerAdds);
          marker.setMap(mapAdd);
          mapAdd.setCenter([lng, lat]); //设置地图中心点
        }

      },
      //修改停车场位置
      changeUpdateMapMarker() {
        let lng = this.modal.update.form.longitude;
        let lat = this.modal.update.form.latitude;
        if (lat != "" && lng != "") {
          let marker = new AMap.Marker({
            icon: new AMap.Icon({
              size: new AMap.Size(40, 40),//图标大小
              imageSize: new AMap.Size(40, 40),
              image: urlSource.imageUrl + "icon/parking.png"
            }),
            position: [lng, lat],
          });
          markerUpdates.push(marker);
          mapUpdate.remove(markerUpdates);
          marker.setMap(mapUpdate);
          mapUpdate.setCenter([lng, lat]); //设置地图中心点
        }

      },
      //获取停车场列表
      getParkingList() {
        let url = urlSource.apiUrl + "parkingLots/" + this.$store.state.user.orgId + "/all";
        if(this.txtSearch){
          url += '?devCode=' + this.txtSearch;
        }
        this.$http.get(url).then(res => {
          res.data.forEach(v => {
            if(v.totalNum==null || v.totalNum=='' || v.totalNum==undefined){
              v.totalNum = 0;
            }
            if(v.useNum==null || v.useNum=='' || v.useNum==undefined){
              v.useNum = 0;
            }
          });
          this.parkingList = res.data
        }).catch(err => {

        })
      },
      //打开新增停车场面板
      openAddModal() {
        this.modal.add.status = true;
        this.orgList.forEach((data) => {
          if(this.modal.add.form.orgId*1==data.id){
            this.modal.add.form.orgName = data.orgName;
          }
        });
        this.initMap();
      },
      //新增停车场
      addLot() {
        this.modal.add.form.userId = this.$store.state.user.userId
        let url = urlSource.apiUrl + "parkingLots/add";
        this.$http.post(url, this.modal.add.form).then(res => {
          if (res.data == true) {
            this.$refs['modal.add.form'].resetFields();
            this.modal.add.status = false;
            this.$Message.success("新增成功!");
            this.getParkingList();
          } else {
            this.$Message.error("新增失败!");
          }
        }).catch(err => {
          this.$Message.error("新增失败!");
        })
      },
      //打开修改停车场面板
      openUpdateModal(params) {
        this.modal.update.status = true;
        this.modal.update.form = JSON.parse(JSON.stringify(params.row));
        this.orgList.forEach((data) => {
          if(this.modal.update.form.orgId*1==data.id){
            this.modal.update.form.orgName = data.orgName;
          }
        });
        this.initUpdateMap(this.modal.update.form.longitude,this.modal.update.form.latitude);
      },
      //修改停车场信息
      updateLot() {
        this.modal.update.form.createTime = new Date();
        let url = urlSource.apiUrl + "parkingLots/update";
        this.$http.put(url, this.modal.update.form).then(res => {
          if (res.data == true) {
            this.modal.update.status = false;
            this.$Message.success("修改成功!");
            this.getParkingList();
          } else {
            this.$Message.error("修改失败!");
          }
        }).catch(err => {
          this.$Message.error("修改失败!");
        })
      },
      //删除停车场
      deleteParking() {
        this.modal.update.form.createTime = new Date();
        let url = urlSource.apiUrl + "parkingLots/" + this.modal.delete.id;
        this.$http.delete(url).then(res => {
          if (res.data == true) {
            this.$Message.success("删除成功!");
            this.getParkingList();
          } else {
            this.$Message.error("删除失败!");
          }
        }).catch(err => {
          this.$Message.error("该停车场里仍有车位不能删除!");
        })
      },
    },
    mounted() {
      this.$nextTick(() => {
        this.getParkingList();
        this.getOrgList();
      })
    }
  }
</script>

<style lang="less">
  .vertical-center-modal {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .ivu-modal {
    top: 2px;
  }
  .codeLb{
    position: absolute;
    padding-top: 6px;
    line-height: 1;
    color: #ed3f14;
    top: 100%;
    left: 0;
  }
</style>
